package pl.streamsoft.currencyApp.parser;

import java.io.StringReader;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

import pl.streamsoft.currencyApp.model.Currency;

public class XMLCurrencyParser implements ICurrencyParser {
	
	@Override
	public List<Currency> getListOfCurrenciesFromStringFile(String file) {		
		List<Currency> listOfCurrencies = new ArrayList<Currency>();
		try {
			DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
			DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
			Document doc = dBuilder.parse(new InputSource(new StringReader(file))); // XHTML, HTML or XML
			doc.getDocumentElement().normalize(); // Puts all Text nodes in the full depth of the sub-tree underneath this Node, It may happen when there's 
			//ignorable whitespace, buffer boundaries, or anywhere else that it was just convenient for the parser. Ignores comments and processing instructions.
			 //Ignores TEXT nodes (likely to exist and contain ignorable whitespace, if not validating. Ignores CDATA nodes and EntityRef nodes.
			
			NodeList nodes = doc.getElementsByTagName("pozycja");
			
			for(int i = 0; i<nodes.getLength(); i++){
				Node node = nodes.item(i);
				
				if(node.getNodeType() == Node.ELEMENT_NODE){
					Element el = (Element) node;
					
					Currency currency = new Currency();
					currency.setName(getValue("nazwa_waluty",el));
					currency.setCurrencyCode(getValue("kod_waluty", el));
					currency.setConverter(Integer.parseInt(getValue("przelicznik", el)));
					currency.setAverageRate(new BigDecimal(getValue("kurs_sredni", el).replace(",", ".")));
					
					listOfCurrencies.add(currency);
				}
				
			}
			
		} 
		catch (Exception e) {
			e.printStackTrace();
		}
		
		return listOfCurrencies;
	}

	private String getValue(String tag, Element el) {
		NodeList nodes = el.getElementsByTagName(tag).item(0).getChildNodes();
		Node node = (Node) nodes.item(0);
		
		return node.getNodeValue();
	}
	

}
